<?php

namespace App\Http\Controllers;

use App\Http\Resources\AccountLogResource;
use App\Http\Resources\AccountResource;
use App\Http\Resources\ProfitListResource;
use App\Models\AccountLog;
use App\Models\Game;
use App\Models\GameCell;
use App\Models\GameOrder;
use App\Models\GamePreOrder;
use Exception;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\Coin;
use App\Models\Account;
use App\Models\User;
use Hashids\Hashids;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;
use Xrfg\Wallet\TRX\Services\TRXWallet;

class AccountController extends Controller
{
    public $typeName = ["质押","质押币转入","转移","收益币转出","兑换","本金返还","当前环收益","上面环收益"];
    public $ringPrifit = ["当前环收益","上面环收益"];
    public $typeNameA = ["收益币转出","当前环收益","上面环收益","兑换","本金返还"];
    public $typeNameB = ["质押","质押币转入","转移"];
    /**
     * USDT钱包账户.
     *
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection|\Illuminate\Http\Response|AccountResource
     */
    public function index()
    {
        /** @var User $user */
        $user = Auth::user();
        $coins = Coin::where('name', 'USDT')->get();
        $accounts = Account::where('user_id', $user->id)->where('coin_id', 1)->get();

        // 得到所拥有账户和所有币种的coin_id差集
        $diffIds = array_values(array_diff(
            $coins->pluck('id')->toArray(),
            $accounts->pluck('coin_id')->toArray()
        ));



        // 用户没有的账户创建生成
        foreach ($diffIds as $id) {
            $account = Account::firstOrCreate([
                'user_id' => $user->id,
                'coin_id' => $id,
            ]);
            $accounts->push($account->fresh());
        }

        foreach ($accounts as $account) {
            if (!$account->address && !app()->isLocal()) {
                $coin = $coins->where('id', $account->coin_id)->first();
                $address = null;
                $tag = null;
                try {
                    switch ($coin->chain_type) {
                        case 'tron':
                            $address = (new TRXWallet(config('wallet.trx.node.wallet')))->newAccount();
                            break;
                        default:
                            break;
                    }
                    if ($address) {
                        Account::where('id', $account->id)->where('address', '=', null)->update(['address' => $address]);
                    }
                } catch (Exception $exception) {
                    Log::error($exception);
                }
            }
        }

        $coinId = Coin::where('name', 'USDT')->value('id');
        /** @var Account $account */
        $account = $accounts->where('coin_id', $coinId)->first();
        if ($account) {
            return new AccountResource($account->refresh()->load('coin'));
        } else {
            return $this->array();
        }
    }

    /**
     * DSE质押钱包、收益钱包账户.
     *
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection|\Illuminate\Http\Response|AccountResource
     */
    public function bp()
    {
        /** @var User $user */
        $user = Auth::user();
        /** @var Coin $coin */
        $coin = Coin::find(2);

        $account = Account::firstOrCreate([
            'user_id' => $user->id,
            'coin_id' => $coin->id,
        ])->refresh();

        $game = Game::orderByDesc('id')->first();
        $buy_invite = '';
        // 节点预购信息
        $pre_status = 0;
        $preOrder = GamePreOrder::where('game_id', $game->id)->where('user_id', $user->id)->orderByDesc('type')->first();
        if ($preOrder && $preOrder->type == 2) {
            $pre_status = 2;
            $buy_invite = (new Hashids(config('hashids.HASHID_SALT'), config('hashids.HASHID_NUMBER')))->encode($preOrder->parent_id);
        } else if ($preOrder && $preOrder->type == 1) {
            $pre_status = 1;
            $buy_invite = (new Hashids(config('hashids.HASHID_SALT'), config('hashids.HASHID_NUMBER')))->encode($preOrder->parent_id);
        }
        // 节点购买信息
        $buy_status = 0;
        $order = GameOrder::where('game_id', $game->id)->where('user_id', $user->id)->orderByDesc('type')->first();
        if ($order && $order->type == 2) {
            $buy_status = 2;
            $buy_invite = (new Hashids(config('hashids.HASHID_SALT'), config('hashids.HASHID_NUMBER')))->encode($order->parent_id);
        } else if ($order && $order->type == 1) {
            $buy_status = 1;
            $buy_invite = (new Hashids(config('hashids.HASHID_SALT'), config('hashids.HASHID_NUMBER')))->encode($order->parent_id);
        }
        // 节点邀请码
        $invite = '';
        if ($buy_status > 0 || $pre_status > 0) { // 购买节点 或 预购节点，才会生成邀请码
            $invite = (new Hashids(config('hashids.HASHID_SALT'), config('hashids.HASHID_NUMBER')))->encode($user->id);
        }
        // 我的节点
        $location = '';
        GameOrder::where('game_id', $game->id)->where('user_id', $user->id)->get()->each(function ($order) use (&$location) {
            $location .= ' ' . $order->location;
        });
        // 我的能量总环数
        $my_cell = GameCell::where('game_id', $game->id)->where('user_id', $user->id)->count() * 100 + GameCell::where('game_id', $game->id)->where('user_id', $user->id)->sum('add_row');
        // 未分配环数
        $unfinish_cell = 0;
        GameCell::where('game_id', $game->id)->where('user_id', $user->id)->get()->each(function ($cell) use (&$unfinish_cell, $game) {
            $unfinish_cell += ($cell->last_row >= $game->current_row ? ($cell->last_row - $game->current_row + 1) : 0);
        });
        // 已分配环数
        $finish_cell = $my_cell - $unfinish_cell;
        return $this->array([
            'name' => $coin->name,
            // 质押币可用余额
            'available' => bcadd($account->available, 0, 4),
            // 质押币冻结余额
            'disabled' => bcadd($account->disabled, 0, 4),
            // 收益币余额
            'profit' => bcadd($account->freeze, 0, 4),
            // DSE收益币划转手续费
            'transfer_out_fee' => 0.1,
            // DSE收益币兑换价格
            'exchange_price' => bcadd(Game::orderByDesc('id')->value('price'), 0, 2),
            // 节点邀请码
            'invite' => $invite,
            // 团队人数
           // 'team_num' => GameOrder::where('game_id', $game->id)->where('parent_id', $user->id)->select('user_id')->distinct()->get()->count(),
            'team_num' => count(User::recomendCount($user->id)),
            // 节点预购信息
            'pre_status' => $pre_status,
            // 节点购买信息
            'buy_status' => $buy_status,
            // 已购买节点使用的邀请码
            'buy_invite' => $buy_invite,
            // 我的节点
            'location' => $location,
            // 我的能量总环数
            'my_cell' => $my_cell,
            // 已分配环数
            'finish_cell' => $finish_cell,
            // 未分配环数
            'unfinish_cell' => $unfinish_cell
        ]);
    }

    /**
     * DSE质押钱包明细.
     * @param Request $request
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     */
    public function bpLog(Request $request)
    {
        $type = $request->query('type'); // 1-获取，2-解冻，3-兑换，4-支出
        $time = $request->query('time');
        $perPage = $request->query('per_page', 15);
        $perPage = $perPage > 100 ? 100 : $perPage;
        $typeNameB = $this->typeNameB;
        // 时间查询（默认7天内）
        $from_date = Carbon::parse('-7 day')->toDateTimeString();
        $to_date = Carbon::now()->toDateTimeString();
        if($time == 7 ){
            $to_date = $from_date;
            $from_date = Carbon::parse('-1 month')->toDateTimeString();
        }elseif($time == 1){
            $from_date = "2020-01-01";
            $to_date = Carbon::parse('-1 month')->toDateTimeString();
        }
        $accountLogs = AccountLog::where('user_id', Auth::id())
            ->where('coin_id', 2)
            ->when(in_array($type, [1,2,3]), function (Builder $query) use ($type,$typeNameB) {
                return $query->where('type', $typeNameB[$type-1]);
            })
            ->when(!in_array($type, [1,2,3]), function (Builder $query) use ($typeNameB) {
                return $query->whereIn('type', $typeNameB);
            })
            ->whereBetween('time',array($from_date, $to_date))
            ->orderByDesc('id')
            ->paginate($perPage)
            ->appends($request->only(['type', 'year', 'month', 'per_page']));

        return AccountLogResource::collection($accountLogs);
    }

    /**
     * DSE收益钱包明细.
     * @param Request $request
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     */
    public function profitList(Request $request)
    {
        $type = $request->query('type'); // 1-获取，2-解冻，3-兑换，4-支出
        $year = $request->query('year');
        $month = $request->query('month');
        $perPage = $request->query('per_page', 15);
        $perPage = $perPage > 100 ? 100 : $perPage;
        $ringPrifit = $this->ringPrifit;
        $typeNameA = $this->typeNameA;
        // 时间查询（默认7天内）
        $from_date = Carbon::parse('-7 day')->toDateTimeString();
        $to_date = Carbon::now()->toDateTimeString();
        if($time == 7 ){
            $to_date = $from_date;
            $from_date = Carbon::parse('-1 month')->toDateTimeString();
        }elseif($time == 1){
            $from_date = "2020-01-01";
            $to_date = Carbon::parse('-1 month')->toDateTimeString();
        }
        $accountLogs = AccountLog::where('user_id', Auth::id())
            ->where('coin_id', 2)
            ->when(in_array($type, [4,5,6,7]), function (Builder $query) use ($type,$typeNameA,$ringPrifit) {
                if (7 == $type) { // 环收益
                    return $query->whereIn('type',  $ringPrifit);
                } else { 
                    return $query->where('type', $typeNameA[$type-1]);
                } 
            })
            ->when(!in_array($type, [4,5,6,7]), function (Builder $query) use ($typeNameA) {
                return $query->whereIn('type', $typeNameA);
            })
            ->whereBetween('time',array($from_date, $to_date))
            ->orderByDesc('id')
            ->paginate($perPage)
            ->appends($request->only(['type', 'year', 'month', 'per_page']));

        return AccountLogResource::collection($accountLogs);
    }


    /**
     * 我的奖励（静态奖励释放 + 推荐奖励释放 + 领导奖励释放）.
     *
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     */
    public function profitLog(Request $request)
    {
        $per_page = $request->input('per_page', 15);
        $leaderList = AccountLog::where('user_id', Auth::id())
            ->where('coin_id', 1)
            ->where('account_type', 'available')
            ->orderBy('id', 'desc')
            ->paginate($per_page)
            ->appends($request->only(['per_page']));

        return ProfitListResource::collection($leaderList);
    }
}
